package cn.danger.com.presenter;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

import java.util.List;
import java.util.Map;

import cn.bmob.v3.BmobObject;
import cn.danger.com.app.MyApplication;
import cn.danger.com.db.MemoDaoImpl;
import cn.danger.com.db.OperateDaoImpl;
import cn.danger.com.model.action.MemoModel;
import cn.danger.com.model.action.MemoModelImpl;
import cn.danger.com.model.entity.Memo;
import cn.danger.com.model.entity.Operate;
import cn.danger.com.model.listener.OnCommonListener;
import cn.danger.com.util.Constants;
import cn.danger.com.util.FileCacheService;
import cn.danger.com.util.MyNetManager;
import cn.danger.com.util.SortUtil;
import cn.danger.com.view.CommonView;

/**
 * Created by 俊 on 2016/12/31.
 */
public class MemoPresenterImpl implements MemoPresenter {

    private Context context;
    private CommonView view;
    private MemoModel model;

    public MemoPresenterImpl(Context context, CommonView view) {
        this.context = context;
        this.view = view;
        model = new MemoModelImpl(context);
    }

    @Override
    public void addMemo(final Memo memo) {
        final long mills = System.currentTimeMillis();
        if (MyApplication.getOperateCode() == Constants.NETWORK) {
            view.showDialog();
            memo.setDate(mills + "");
            model.addMemoToNetwork(memo, new OnCommonListener() {
                @Override
                public void onSuccess(String objectId) {
                    Memo new_memo = new Memo();
                    new_memo.setId(memo.getId());
                    new_memo.setUsername(memo.getUsername());
                    new_memo.setContent(memo.getContent());
                    new_memo.setTitle(memo.getTitle());
                    new_memo.setObjectId(objectId);
                    new_memo.setDate(mills + "");
                    new MemoDaoImpl(context).insert(new_memo);
                    view.hideDialog();
                    view.showMessage(Constants.SUCCESS_TO_ADD_MEMO);
                }

                @Override
                public void onError(String error) {
                    view.hideDialog();
                    view.showMessage(error);
                }
            });
        } else if (MyApplication.getOperateCode() == Constants.LOCAL || MyApplication.getOperateCode() == Constants.NOT_LOGIN) {
            String check_result = model.check(memo);
            if (check_result.equals(Constants.IS_RIGHT)) {
                try {
                    memo.setDate(mills + "");
                    int id = new MemoDaoImpl(context).insert(memo);
                    Operate operate = new Operate();
                    operate.setUsername(memo.getUsername());
                    operate.setOperate_table("memo");
                    operate.setOperate_type("add");
                    operate.setOperate_id(id);
                    new OperateDaoImpl(context).insert(operate);
                    view.showMessage(Constants.SUCCESS_TO_SAVE_LOCAL);
                } catch (Exception e) {
                    e.printStackTrace();
                    view.showMessage(Constants.FAIL_TO_SAVE_LOCAL);
                }
            } else {
                view.showMessage(check_result);
            }
        }
    }

    @Override
    public void updateMemo(final Memo memo) {
        final long mills = System.currentTimeMillis();
        if (MyApplication.getOperateCode() == Constants.NETWORK) {
            view.showDialog();
            memo.setDate(mills + "");
            model.updateMemoToNetWork(memo, new OnCommonListener() {
                @Override
                public void onSuccess(String objectId) {
                    Memo new_memo = new Memo();
                    new_memo.setUsername(memo.getUsername());
                    new_memo.setContent(memo.getContent());
                    new_memo.setTitle(memo.getTitle());
                    new_memo.setId(memo.getId());
                    new_memo.setObjectId(memo.getObjectId());
                    new_memo.setDate(mills + "");
                    new MemoDaoImpl(context).update(new_memo);
                    view.hideDialog();
                    view.showMessage(Constants.SUCCESS_TO_UPDATE_MEMO);
                }

                @Override
                public void onError(String error) {
                    view.hideDialog();
                    view.showMessage(error);
                }
            });
        } else if (MyApplication.getOperateCode() == Constants.LOCAL || MyApplication.getOperateCode() == Constants.NOT_LOGIN) {
            String check_result = model.check(memo);
            if (check_result.equals(Constants.IS_RIGHT)) {
                try {
                    memo.setDate(mills + "");
                    new MemoDaoImpl(context).update(memo);
                    Operate operate = new Operate();
                    operate.setUsername(memo.getUsername());
                    operate.setOperate_table("memo");
                    operate.setOperate_id(memo.getId());
                    operate.setOperate_objectId(memo.getObjectId());
                    operate.setOperate_type("update");
                    new OperateDaoImpl(context).insert(operate);
                    view.showMessage(Constants.SUCCESS_TO_UPDATE_LOCAL);
                } catch (Exception e) {
                    view.showMessage(Constants.FAIL_TO_UPDATE_LOCAL);
                }
            } else {
                view.showMessage(check_result);
            }
        }
    }

    @Override
    public void deleteMemo(final Memo memo) {
        final long mills = System.currentTimeMillis();
        if (MyApplication.getOperateCode() == Constants.NETWORK) {
            view.showDialog();
            memo.setDate(mills + "");
            model.deleteMemoToNetWork(memo.getObjectId(), new OnCommonListener() {
                @Override
                public void onSuccess(String message) {
                    new MemoDaoImpl(context).delete(memo.getId());
                    view.hideDialog();
                    view.showMessage(Constants.SUCCESS_TO_DELETE_MEMO);
                }

                @Override
                public void onError(String error) {
                    view.hideDialog();
                    view.showMessage(error);
                }
            });
        } else if (MyApplication.getOperateCode() == Constants.LOCAL || MyApplication.getOperateCode() == Constants.NOT_LOGIN) {
            try {
                new MemoDaoImpl(context).delete(memo.getId());
                Operate operate = new Operate();
                operate.setUsername(memo.getUsername());
                operate.setOperate_objectId(memo.getObjectId());
                operate.setOperate_id(memo.getId());
                operate.setOperate_type("delete");
                operate.setOperate_table("memo");
                new OperateDaoImpl(context).insert(operate);
                view.showMessage(Constants.SUCCESS_TO_DELETE_LOCAL);
            } catch (Exception e) {
                view.showMessage(Constants.FAIL_TO_DELETE_LOCAL);
            }
        }
    }

    @Override
    public void deleteMemos(final List<BmobObject> memos) {
        if (MyApplication.getOperateCode() == Constants.NETWORK) {
            view.showDialog();
            model.deleteMemosToNetWork(memos, new OnCommonListener() {
                @Override
                public void onSuccess(String message) {
                    for (int i = 0; i < memos.size(); i++) {
                        Memo memo = (Memo) memos.get(i);
                        new MemoDaoImpl(context).delete(memo.getId());
                    }
                    view.hideDialog();
                    view.showMessage(message);
                }

                @Override
                public void onError(String error) {
                    view.hideDialog();
                    view.showMessage(error);
                }
            });
        } else if (MyApplication.getOperateCode() == Constants.LOCAL || MyApplication.getOperateCode() == Constants.NOT_LOGIN) {
            try {
                for (int i = 0; i < memos.size(); i++) {
                    Memo memo = (Memo) memos.get(i);
                    new MemoDaoImpl(context).delete(memo.getId());
                    Operate operate = new Operate();
                    operate.setUsername(memo.getUsername());
                    operate.setOperate_id(memo.getId());
                    operate.setOperate_table("memo");
                    operate.setOperate_objectId(memo.getObjectId());
                    operate.setOperate_type("delete");
                    new OperateDaoImpl(context).insert(operate);
                }
                view.showMessage(Constants.SUCCESS_TO_DELETE_LOCAL);
            } catch (Exception e) {
                view.showMessage(Constants.FAIL_TO_DELETE_LOCAL);
            }
        }
    }

    @Override
    public List<Memo> getMemos() {
        FileCacheService service = new FileCacheService(context);
        Map<String, String> map = (Map<String, String>) service.getSharePreference("userInfo");
        List<Memo> default_memos = new MemoDaoImpl(context).getMemos("default");
        if (map.get("phone") != null) {
            List<Memo> memos = new MemoDaoImpl(context).getMemos(map.get("phone"));
            if (memos == null) {
                return SortUtil.sortMemos(default_memos);
            } else {
                if (default_memos != null) {
                    memos.addAll(default_memos);
                }
            }
            return SortUtil.sortMemos(memos);
        } else {
            if (default_memos != null) {
                return SortUtil.sortMemos(default_memos);
            }
        }
        return null;
    }

    @Override
    public void synchronousMemo() {
        if (new MyNetManager(context).isNetworkAvailable()) {
            if (MyApplication.getOperateCode() != Constants.NOT_LOGIN) {
                synchronous();
            } else {
                view.showMessage(Constants.PLEASE_LOGIN);
            }
        } else {
            view.showMessage(Constants.NETWORK_IS_NOT_AVAILABLE);
        }
    }

    private void synchronous() {
        FileCacheService service = new FileCacheService(context);
        Map<String, String> map = (Map<String, String>) service.getSharePreference("userInfo");
        if (map.get("phone") != null) {
            view.showDialog();
            //获取Operate表内操作的Memo数据
            List<Operate> operates = new OperateDaoImpl(context).queryOperates(map.get("phone"), "memo");
            List<Operate> default_operates = new OperateDaoImpl(context).queryOperates("default", "memo");
            List<Memo> memos = new MemoDaoImpl(context).getMemos("default");
            if (memos != null) {
                for (Memo memo : memos) {
                    memo.setUsername(map.get("phone"));
                    new MemoDaoImpl(context).update(memo);
                }
            }
            if (default_operates != null) {
                for (Operate operate : default_operates) {
                    operate.setUsername(map.get("phone"));
                    new OperateDaoImpl(context).insert(operate);
                    operates.add(operate);
                }
            }
            Log.i("danger", "operate--->>" + operates);
            //遍历在离线时所有对Memo表的操作
            for (final Operate operate : operates) {
                //如果对Memo的操作是添加
                if (operate.getOperate_type().equals("add")) {
                    final Memo memo = new MemoDaoImpl(context).getMemo(operate.getOperate_id());
                    //向服务器添加Memo实体
                    model.addMemoToNetwork(memo, new OnCommonListener() {
                        @Override
                        public void onSuccess(String objectId) {
                            //删除Operate表内的记录
                            new OperateDaoImpl(context).delete(operate);
                            //将服务器返回的objectId设置给Memo并保存
                            Memo new_memo = new Memo();
                            new_memo.setId(memo.getId());
                            new_memo.setUsername(memo.getUsername());
                            new_memo.setDate(memo.getDate());
                            new_memo.setTitle(memo.getTitle());
                            new_memo.setContent(memo.getContent());
                            new_memo.setObjectId(objectId);
                            new MemoDaoImpl(context).update(new_memo);
                            Intent intent = new Intent("update_ui");
                            context.sendBroadcast(intent);
                        }

                        @Override
                        public void onError(String error) {
                            view.showMessage(error);
                        }
                    });
                    //如果对Memo的操作是删除
                } else if (operate.getOperate_type().equals("delete")) {
                    //获取Memo实体
                    model.deleteMemoToNetWork(operate.getOperate_objectId(), new OnCommonListener() {
                        @Override
                        public void onSuccess(String message) {
                            new OperateDaoImpl(context).delete(operate);
                        }

                        @Override
                        public void onError(String error) {
                            view.showMessage(error);
                        }
                    });
                    //如果对Memo的操作是更新
                } else if (operate.getOperate_type().equals("update")) {
                    //获取Memo实体
                    final Memo memo = new MemoDaoImpl(context).getMemo(operate.getOperate_id());
                    model.updateMemoToNetWork(memo, new OnCommonListener() {
                        @Override
                        public void onSuccess(String message) {
                            new OperateDaoImpl(context).delete(operate);
                        }

                        @Override
                        public void onError(String error) {
                            view.showMessage(error);
                        }
                    });
                }
            }
            view.hideDialog();
            view.showMessage(Constants.SUCCESS_TO_SYNCHRONOUS_MEMO);
        } else {
            view.showMessage(Constants.PLEASE_LOGIN);
        }
    }
}
